package com.dlc.shop.multishop.controller;

import com.dlc.shop.bean.model.ImAutoReply;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ResponseEnum;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.security.common.util.AuthUserContext;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.ImAutoReplyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


/**
 * 客服自动回复
 * @author TRACK
 */
@RestController
@RequestMapping("/shop/imAutoReply")
@Tag(name = "店铺客服自动回复")
@AllArgsConstructor
public class ImAutoReplyController {

    private final ImAutoReplyService imAutoReplyService;

    @GetMapping("/info")
    @Operation(summary = "获取客服自动回复")
    @PreAuthorize("@pms.hasPermission('shop:imAutoReply:get')")
    public ServerResponseEntity<ImAutoReply> getById() {
        Long shopId = AuthUserContext.getShopId();
        ImAutoReply imAutoReply = imAutoReplyService.getByShopId(shopId);
        return ServerResponseEntity.success(imAutoReply);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('shop:imAutoReply:save')")
    @Operation(summary = "保存客服自动回复", description = "保存客服自动回复")
    public ServerResponseEntity<Void> save(@RequestBody @Valid ImAutoReply imAutoReply) {
        imAutoReply.setShopId(AuthUserContext.getShopId());
        ImAutoReply autoReply = imAutoReplyService.getByShopId(imAutoReply.getShopId());
        if (Objects.nonNull(autoReply)) {
            throw new YamiShopBindException("自动回复已存在");
        }
        imAutoReplyService.insert(imAutoReply);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('shop:imAutoReply:update')")
    @Operation(summary = "更新客服自动回复", description = "更新客服自动回复")
    public ServerResponseEntity<Void> update(@RequestBody @Valid ImAutoReply imAutoReply) {
        ImAutoReply dbImAutoReply = imAutoReplyService.getById(imAutoReply.getAutoReplyId());
        if (Objects.nonNull(dbImAutoReply) && !Objects.equals(dbImAutoReply.getShopId(), AuthUserContext.getShopId())) {
            throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED);
        }
        imAutoReply.setShopId(SecurityUtils.getShopUser().getShopId());
        imAutoReplyService.updateContent(imAutoReply);
        return ServerResponseEntity.success();
    }
}
